package middleware

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"note.zhiwangyunchuang.com/common"
	"note.zhiwangyunchuang.com/model"
	"note.zhiwangyunchuang.com/network"
	"strings"
)

func AuthMiddleware() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		// 获取header中的token
		tokenString := ctx.GetHeader("Authorization")
		fmt.Println("tokenString=======>", tokenString)
		// 验证token格式
		if tokenString == "" || !strings.HasPrefix(tokenString, "Bearer ") {
			network.Fail(ctx, "权限不足", gin.H{})
			ctx.Abort()
			return
		}

		// 解析token
		tokenString = tokenString[7:]
		token, claims, err := common.ParseToken(tokenString)
		if err != nil || !token.Valid {
			network.Fail(ctx, "权限不足", gin.H{})
			ctx.Abort()
			return
		}

		//token验证通过
		userId := claims.UserId
		Db := common.GetDb()
		var user model.User
		Db.First(&user, userId)
		if user.ID == 0 {
			network.Fail(ctx, "权限不足", gin.H{})
			ctx.Abort()
			return
		}

		// 用户信息存入上下文
		ctx.Set("user", user)

		// 执行后面的操作
		ctx.Next()
	}
}
